<template>
  <div class="page-container">
    <!--工具栏-->
    <div class="toolbar" style="float:left;padding-top:10px;padding-left:15px;">
      <el-form :inline="true" :model="filters" :size="size">
        <el-form-item>
          <el-input v-model="filters.userName" placeholder="用户名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="filters.nickName" placeholder="昵称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="filters.mobile" placeholder="手机号"></el-input>
        </el-form-item>
        <el-form-item>
          <perm-button icon="fa fa-search" label="搜索" perms="sys:user:list" type="primary" @click="findPage(null)"/>
        </el-form-item>
        <el-form-item>
          <perm-button icon="fa fa-plus" label="新增" perms="sys:user:add" type="success" @click="handleAdd"/>
        </el-form-item>
      </el-form>
    </div>
    <div class="toolbar" style="float:right;padding-top:10px;padding-right:15px;">
      <el-form :inline="true" :size="size">
        <el-form-item>
          <el-button-group>
            <el-tooltip content="刷新" placement="top">
              <el-button icon="fa fa-refresh" @click="findPage(null)"></el-button>
            </el-tooltip>
            <el-tooltip content="列显示" placement="top">
              <el-button icon="fa fa-filter" @click="displayFilterColumnsDialog"></el-button>
            </el-tooltip>
            <el-tooltip content="导出" placement="top">
              <el-button icon="fa fa-file-excel-o"></el-button>
            </el-tooltip>
          </el-button-group>
        </el-form-item>
      </el-form>
      <!--表格显示列界面-->
      <table-column-filter-dialog ref="tableColumnFilterDialog" :columns="columns"
                                  @handleFilterColumns="handleFilterColumns">
      </table-column-filter-dialog>
    </div>
    <!--表格树内容栏-->
    <perm-table :page="page" :columns="columns" :selectionChange="selectionChange"
                :handleCurrentHandle="handleCurrentHandle" :loading="loading" size="mini"
                @findPage="findPage" @handleEdit="handleEdit" @handleDelete="handleDelete"
                permsEdit="sys:user:update" permsDelete="sys:user:delete">
    </perm-table>
    <!-- 新增修改界面 -->
    <el-dialog :title="!dataForm.userId ? '新增用户' : '修改用户'" width="30%" :visible.sync="dialogVisible" :close-on-click-modal="false">
      <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="submitForm()"
               label-width="80px" :size="size" style="text-align:left;">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="dataForm.userName" placeholder="用户名" autocomplete="off" maxlength="64"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickName">
          <el-input v-model="dataForm.nickName" placeholder="昵称" autocomplete="off" maxlength="64"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="dataForm.mobile" placeholder="手机号" maxlength="11"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="dataForm.email" placeholder="邮箱" autocomplete="off" maxlength="64"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="dataForm.password" show-password placeholder="密码" @change="handlePwdChange" autocomplete="off" maxlength="64"></el-input>
        </el-form-item>
        <el-form-item v-if="dataForm.userId <= 0" label="确认密码" prop="checkPass">
          <el-input v-model="dataForm.checkPass" show-password placeholder="确认密码" autocomplete="off" maxlength="64"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="roleIds">
          <el-select v-model="dataForm.roleIds" multiple placeholder="请选择" style="width:100%">
            <el-option
              v-for="item in roleList"
              :key="item.roleId"
              :label="item.roleName"
              :value="item.roleId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="启用状态" prop="available">
          <el-switch
            v-model="dataForm.available"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-value="启用"
            inactive-value="禁用">
          </el-switch>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button :size="size"  @click="dialogVisible = false">取消</el-button>
        <el-button :size="size"  type="primary" :loading="editLoading" @click="submitForm()">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import PopupTreeInput from '../../Component/PopupTreeInput/Index'
import PermButton from '../../Component/PermButton/Index'
import PermTable from '../../Component/PermTable/Index'
import TableColumnFilterDialog from '../../Component/TableColumnFilterDialog/Index'

export default {
    name: 'User',
    components: {
        PermTable,
        PermButton,
        PopupTreeInput,
        TableColumnFilterDialog
    },
    data: function() {
        var validateUserName = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('用户名不能为空'))
            } else if (!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(value)) {
                callback(new Error('用户名须以字母开头，且只能包含英文字母、数字、下划线'))
            } else {
                callback()
            }
        }
        var validateNickName = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('昵称不能为空'))
            } else if (!/^[\u4E00-\u9FA5A-Za-z0-9]+$/.test(value)) {
                callback(new Error('昵称只能是中文、英文、数字的任意组合，但不能包含特殊符号'))
            } else {
                callback()
            }
        }
        var validatePassword = (rule, value, callback) => {
            // 密码喂修改则不校验
            if (!this.isPwdModified) {
                callback()
                return
            }
            if (value === '') {
                callback(new Error('密码长度为6~64位大小字母、数字及特殊字符组成'))
            } else if (value.length < 6) {
                callback(new Error('密码长度至少6位'))
            } else if (value.length > 64) {
                callback(new Error('密码长度为6~64位大小字母、数字及特殊字符组成'))
            } else if (!/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[\s\S]{6,64}$/.test(value)) {
                callback(new Error('密码必须包含大写字母、小写字母与数字'))
            } else if (this.dataForm.checkPass !== '') {
                this.$refs.dataForm.validateField('chechPass')
                callback()
            } else {
                callback()
            }
        }
        var validateCheckPass = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入密码'))
            } else if (value !== this.dataForm.password) {
                callback(new Error('两次输入密码不一致!'))
            } else {
                callback()
            }
        }

        var validateMobile = (rule, value, callback) => {
            if (value === '') {
                callback()
            } else if (!/^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/.test(value)) {
                callback(new Error('请输入正确的手机号码'))
            } else {
                callback()
            }
        }
        var validateEmail = (rule, value, callback) => {
            if (value === '') {
                callback()
            } else if (!/^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value)) {
                callback(new Error('请输入正确的邮箱'))
            } else {
                callback()
            }
        }
        return {
            size: 'small',
            loading: false,
            editLoading: false,
            filters: {
                userName: '',
                nickName: '',
                mobile: ''
            },
            filterColumns: [],
            columns: [],
            page: {},
            pageRequest: {
                current: 1,
                size: 10
            },
            availableList: ['启用', '禁用'],
            dialogVisible: false,
            dataForm: {
                userId: 0,
                userName: '',
                nickName: '',
                mobile: '',
                email: '',
                password: '',
                checkPass: '',
                available: '',
                roleIds: []
            },
            isPwdModified: false,
            roleList: [],
            dataRule: {
                userName: [{ required: true, message: '用户名不能为空', trigger: 'blur' }, { validator: validateUserName, trigger: 'blur' }],
                nickName: [{ required: true, message: '昵称不能为空', trigger: 'blur' }, { validator: validateNickName, trigger: 'blur' }],
                password: [{ required: true, message: '密码不能为空', trigger: 'blur' }, { validator: validatePassword, trigger: 'blur' }],
                checkPass: [{ validator: validateCheckPass, trigger: 'blur' }],
                mobile: [{ validator: validateMobile, trigger: 'blur' }],
                email: [{ validator: validateEmail, trigger: 'blur' }]
            }
        }
    },
    methods: {
    // 获取分页数据
        findPage: function(data) {
            this.loading = true
            if (data != null) {
                this.pageRequest = data.pageRequest
            }
            let param = {
                userName: this.filters.userName
            }
            param = Object.assign(param, this.pageRequest)
            this.$api.user.getUserList(param).then(res => {
                if (res && !res.success) {
                    this.$message({ message: res.message, type: 'error' })
                    this.loading = false
                    return
                }
                this.page = res.data
                this.loading = false
                this.findRole()
            }).then(data != null ? data.callback : '')
        },
        findRole: function() {
            this.$api.user.getRoleList().then(res => {
                if (res && !res.success) {
                    this.$message({ message: res.message, type: 'error' })
                    return
                }
                this.roleList = res.data
            })
        },
        // 显示新增界面
        handleAdd: function() {
            this.dialogVisible = true
            this.isPwdModified = true
            this.dataForm = {
                userId: 0,
                userName: '',
                nickName: '',
                mobile: '',
                email: '',
                password: '',
                checkPass: '',
                available: '启用',
                roleIds: []
            }
        },
        // 显示编辑界面
        handleEdit: function(data) {
            this.dialogVisible = true
            this.isPwdModified = false
            Object.assign(this.dataForm, data.row)
        },
        handlePwdChange: function(val) {
            this.isPwdModified = true
        },
        // 删除
        handleDelete(data) {
            this.$confirm('确认删除选中记录吗？', '提示', {
                type: 'warning'
            }).then(() => {
                const params = this.getDeleteIds([], data.row)
                this.$api.user.deleteUser(params).then(res => {
                    if (!res.success) {
                        this.$message({ message: res.message, type: 'error' })
                        return
                    }
                    this.findPage(null)
                    this.$message({ message: '删除成功', type: 'success' })
                })
            })
        },
        // 获取删除的包含子分类的id列表
        getDeleteIds(ids, row) {
            ids.push(row.userId)
            if (row.children != null) {
                for (let i = 0, len = row.children.length; i < len; i++) {
                    this.getDeleteIds(ids, row.children[i])
                }
            }
            return ids
        },
        selectionChange(selections) {
            console.log(selections)
        },
        handleCurrentHandle: function(val) {
            console.log(val)
        },
        // 表单提交
        submitForm() {
            var callback = (res) => {
                this.editLoading = false
                if (res.success) {
                    this.$message({ message: '操作成功', type: 'success' })
                    this.$refs['dataForm'].resetFields()
                    this.dialogVisible = false
                } else {
                    this.$message({
                        message: res.message,
                        type: 'error'
                    })
                }
                // 当前页
                this.findPage(null)
            }
            this.$refs['dataForm'].validate(valid => {
                if (valid) {
                    this.$confirm('确认提交吗？', '提示', {}).then(() => {
                        this.editLoading = true
                        const params = Object.assign({}, this.dataForm)
                        params.available = this.availableList.findIndex(item => item === params.available)
                        if (!this.dataForm.userId) {
                            this.$api.user.saveUser(params).then(res => {
                                callback(res)
                            })
                        } else {
                            this.$api.user.updateUser(params).then(res => {
                                callback(res)
                            })
                        }
                    })
                }
            })
        },
        // 初始化表格
        initColums: function() {
            this.columns = [
                { prop: 'userId', label: '用户ID', minWidth: 120 },
                { prop: 'userName', label: '用户名', minWidth: 200 },
                { prop: 'nickName', label: '昵称', minWidth: 200 },
                { prop: 'roleNames', label: '角色', minWidth: 200 },
                { prop: 'mobile', label: '手机号', minWidth: 150 },
                { prop: 'email', label: '邮箱', minWidth: 150 },
                { prop: 'available', label: '启用状态', minWidth: 150 },
                { prop: 'updateTime', label: '更新时间', minWidth: 200 }
            ]
            this.filterColumns = JSON.parse(JSON.stringify(this.columns))
        },
        // 处理表格列过滤显示
        displayFilterColumnsDialog: function() {
            this.$refs.tableColumnFilterDialog.setDialogVisible(true)
        },
        // 处理表格列过滤显示
        handleFilterColumns: function(data) {
            this.filterColumns = data.filterColumns
            this.$refs.tableColumnFilterDialog.setDialogVisible(false)
        }
    },
    mounted() {
        this.initColums()
        this.findPage(null)
    }
}
</script>

<style scoped>
</style>
